package mapper

import (
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

// https://cloud.tencent.com/developer/article/1986655?from=15425&areaSource=102001.1&traceId=aHc3b3_e7chTQc6nT1ybj
var (
	friendSql string = "select distinct u.user_id   userId," +
		"\n                u.name      userName," +
		"\n                u.password," +
		"\n                u2.user_id  friendUserId," +
		"\n                u2.name     friendUserName," +
		"\n                u2.password friendPassword" +
		"\n from user u" +
		"\n         inner join users us on u.id = us.user_id1 or u.id = us.user_id2" +
		"\n         inner join user u2 on u2.id = us.user_id1 or u2.id = us.user_id2" +
		"\n where u.user_id = ? " +
		"\n  and u.user_id != u2.user_id "
)

type Friend struct {
	UserId         int64  `gorm:"column:userId"`
	UserName       string `gorm:"column:userName"`
	Password       string `gorm:"column:password"`
	FriendUserId   int64  `gorm:"column:friendUserId"`
	FriendUserName string `gorm:"column:friendUserName"`
	FriendPassword string `gorm:"column:friendPassword"`
}

func Friends(userId int64, db *gorm.DB) []Friend {
	var friends []Friend
	tx := db.Debug().Raw(friendSql, userId).Model(Friend{}).Scan(&friends)
	//tx := db.Debug().Raw(friendSql, userId).Model(Friend{}).Find(&friends)
	if tx.Error != nil {
		logx.Error(tx.Error)
		panic(tx.Error)
	}
	if tx.RowsAffected == 0 {
		return nil
	}
	return friends
}
